package com.lyl.goods.controller;

import com.lyl.goods.pojo.User;
import com.lyl.goods.respository.AdminRepository;
import com.lyl.goods.utils.Md5Util;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.time.LocalDateTime;

import static com.lyl.goods.msg.Message.*;


@Controller
@Slf4j
public class AdminController {
    @Resource
    private AdminRepository adminRepository;

    /**
     * @Description: 注册接口
     * @Author: liyunlong
     * @Date: 2024/3/1
     */

    @GetMapping("/register")
    public String showRegisterForm() {
        return "register";
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(@RequestParam("username") @Pattern(regexp = "^\\S{5,16}$") String username, @RequestParam("password") @Pattern(regexp = "^\\S{5,16}$") String password, Model model, HttpSession session) {
        User user = adminRepository.findByUsername(username);
        User user1 = new User();
        user1.setUsername(username);
        password = Md5Util.getMD5String(password);
        user1.setPassword(password);
        user1.setCreateTime(LocalDateTime.now());

        if (user == null) {
            log.info("用户注册，注册用户名为：{}", username);
            adminRepository.save(user1);
            return "redirect:/login";
        } else {
            log.info(USER_EXITS);
            return "register";
        }
    }

    /**
     * @Description: 登录接口
     * @Author: liyunlong
     * @Date: 2024/3/1
     */
    @GetMapping("/login")
    public String showLoginForm() {
        return "login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(@RequestParam("username") @Pattern(regexp = "^\\S{5,16}$") String username, @RequestParam("password") @Pattern(regexp = "^\\S{5,16}$") String password, HttpSession session) {
        User user = adminRepository.findByUsername(username);
        if (user == null) {
            log.info(USER_ERROR);
            return "login";
        }
        if (Md5Util.getMD5String(password).equals(user.getPassword()) && password != null) {
            log.info("管理员：{}，登录成功", username);
//存userid
            session.setAttribute("userId", user.getId());
            session.setAttribute("currentUser", user.getUsername());
            return "redirect:/product";
        } else {
            log.info(PASSWORD_ERROR);
            return "login";
        }
    }
}
